package com.example.demo.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.HexUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

@Slf4j
public class AESUtil {

    /**
     * 加密
     * @param content
     * @param key
     * @return
     */
    public static byte[] encrypt(String content,String key){
        try{
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(key.getBytes("utf-8")));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] result = cipher.doFinal(byteContent);// 加密
            return result;
        }catch (Exception e){
            log.error("",e);
        }

        return null;
    }

    /**
     * 加密成字符串
     * @param content
     * @param key
     * @return
     */
    public static String encryptToString(String content,String key){
        try{
            byte[] byteResult = encrypt(content,key);
            if(byteResult != null){
                return HexUtils.toHexString(byteResult);
            }
        }catch (Exception e){
            log.error("",e);
        }
        return null;
    }

    /**
     * 解密
     * @param content
     * @param password
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();// 根据用户密码，生成一个密钥
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
            byte[] result = cipher.doFinal(content);
            return result; // 明文

        } catch (Exception e) {
            log.error("",e);
        }
        return null;
    }

    /**
     * 解密成字符串
     * @param content
     * @param key
     * @return
     */
    public static String decryptToString(String content,String key){
        try{
            byte[] byteResult = decrypt(HexUtils.fromHexString(content),key);

            return new String(byteResult,"utf-8");

        }catch (Exception e){
            log.error("",e);
        }

        return null;
    }
}
